package org.ttitfly.ttcore.service.menu;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.PropertyFilter.MatchType;
import org.ttitfly.ttcore.dao.menu.SystemMenuDao;
import org.ttitfly.ttcore.entity.account.Role;
import org.ttitfly.ttcore.entity.account.User;
import org.ttitfly.ttcore.entity.menu.SystemMenu;
import org.ttitfly.ttcore.entity.system.Dictionary;
import org.ttitfly.ttcore.util.tree.FlatTreeNode;
import org.ttitfly.ttcore.util.tree.StringComparator;
import org.ttitfly.ttcore.util.tree.TreeNode;
import org.ttitfly.ttcore.util.tree.TreeUtil;

/**

 */
//Spring Bean的标识.
@Component
//默认将类中的所有函数纳入事务管理.
@Transactional
public class SystemMenuManager {
	@Autowired
	private SystemMenuDao systemMenuDao;

	private static Logger logger = LoggerFactory.getLogger(SystemMenuManager.class);
	
	public SystemMenu getSystemMenu(Long id) {
		return systemMenuDao.get(id);
	}
	
	@Transactional(readOnly = true)
	public List<SystemMenu> findBy(String propertyName,Object value, String orderBy, boolean isAsc) {
		return systemMenuDao.findBy( propertyName,  value,  orderBy,  isAsc);
	}
	
	public void saveOrUpdate(SystemMenu entity){
		systemMenuDao.save(entity);
	}
	
	public void remove(Long id){
		systemMenuDao.delete(id);
	}
	
	public void remove(SystemMenu entity){
		systemMenuDao.delete(entity);
	}
	
	public SystemMenu findByProperty(String propertyName,String propertyValue){
		SystemMenu SystemMenu = new SystemMenu();
		List<SystemMenu> list = systemMenuDao.findBy(propertyName,propertyValue,MatchType.EQ);
		if(list != null && list.size()>0){
			SystemMenu = list.get(0); 
		}
		return SystemMenu;
	}
	
	public SystemMenu getById(Long id){
		return systemMenuDao.get(id);
	}
	
	public List<SystemMenu> getByIds(List<Long> ids){
		if (ids != null && ids.size()>0) {
            return systemMenuDao.getByIds(ids);
        } else {
            return new ArrayList<SystemMenu>(0);
        }
	}
	
	public TreeNode buildTree(Long id){
		TreeNode result = null;
		List<FlatTreeNode> flatTreeNodeList = new ArrayList<FlatTreeNode>();
		//所有的孩子结点，包括孩子的孩子
		List<SystemMenu> poList = systemMenuDao.getAllChild(0L);
		SystemMenu root = new SystemMenu();
		root.setId(id);
		root.setTitle("菜单列表");
		root.setLeaf(0);
		root.setParentId(null);
		poList.add(root);//吧本身结点加入
		
		//add privilege list
		for(SystemMenu p : poList){
			flatTreeNodeList.add(new FlatTreeNode("" + p.getId(), p.getTitle(), "" + p.getParentId(), p));
		}
		result = TreeUtil.buildTreeFromFlatTreeNodeList(""+id, flatTreeNodeList, new StringComparator());
		return result;
	}
	
	public List<String> findAllCheckedNode(List<String> checkedNodeKeys){
		List<String> result = new ArrayList<String>();
		if(checkedNodeKeys != null){
			TreeNode root = buildTree(0L);
			result = TreeUtil.findAllCheckedNode(root, checkedNodeKeys);//所有子结点和选中的结点进行对比
		}
		return result;
	}
	
	/**
	 * 根据工作流节点获得能够操作该节点的所有用户
	 * @param secondMenuName 工作流定义名称(二级菜单名称)
	 * @param leafMenuName  工作流节点名称(叶子节点名称)
	 * @param areaId  区域ID
	 * @return
	 */
	public List<User> findUsersByWorkflow(String secondMenuName,String leafMenuName,Long areaId){
		Set<User> userSet = new HashSet<User>();
		List<User> users = new ArrayList<User>();
		SystemMenu fitMenu = null;
		//查找二级菜单
		List<SystemMenu> menus = systemMenuDao.findBy("title", secondMenuName);
		for(SystemMenu menu : menus){
			List<SystemMenu> leafMenus = findBy("parentId", menu.getId(),"id",true);
			for(SystemMenu leafMenu : leafMenus){
				if(leafMenu.getTitle().equals(leafMenuName)){
					fitMenu = leafMenu;
					break;
				}
			}
		}
		if(fitMenu != null){
			List<Role> roles = fitMenu.getRoles();
			for(Role role : roles){
				List<User> userList = role.getUsers();
				for(User user : userList){
					List<Dictionary> dictionarys = user.getAreas();
					for(Dictionary dic : dictionarys){
						if(dic.getId().longValue() == areaId.longValue()){
							userSet.add(user);
							break;
						}
					}
				}
			}
		}
		
		if(userSet.size() > 0){
			users = new ArrayList<User>(userSet);//去重
		}
		return users;
	}
	
}
